import { RequestHandler } from 'express'
import { failure, success } from '@/utils/response'
import payService from '@/services/payService'

const generatePay: RequestHandler = async (req, res) => {
  try {
    const data = await payService.generatePay(req.userId as number, req.body)
    success(res, '支付地址获取成功。', data)
  } catch (error) {
    failure(res, error as Error, '支付地址获取失败：')
  }
}

const finishSync: RequestHandler = async (req, res) => {
  try {
    await payService.finishSync(req.query)
    // success(res, '支付成功。')
    res.send('success')
    // res.redirect('https://www.baidu.com')
  } catch (error) {
    failure(res, error as Error, '支付失败：')
  }
}

const notifyAsync: RequestHandler = async (req, res) => {
  try {
    await payService.notifyAsync(req.query)
    // zfb是固定res.send('success)
    res.send('success')
  } catch (error) {
    failure(res, error as Error, '支付失败(异步)：')
  }
}

/** 主动查询ezf订单状态 */
const queryPayOrder: RequestHandler = async (req, res) => {
  try {
    const data = await payService.queryPayOrder(
      req.userId as number,
      req.query.outTradeNo as string,
    )
    success(res, '订单查询成功。', data)
  } catch (error) {
    failure(res, error as Error, '订单查询失败：')
  }
}

/** 主动更新ezf订单状态 */
const updatePayOrder: RequestHandler = async (req, res) => {
  try {
    await payService.updatePayOrder(req.userId as number, req.query.outTradeNo as string)
    success(res, '订单更新成功，请重新查询订单。')
  } catch (error) {
    failure(res, error as Error, '订单更新失败：')
  }
}

export default {
  generatePay,
  finishSync,
  notifyAsync,
  queryPayOrder,
  updatePayOrder,
}
